package com.zhangjingcheng.yunyixia.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void set(String key, Object value, Integer time) {
        if (time == null || time <= 0) {
            set(key, value); // 无过期时间，调用重载方法
            return;
        }
        redisTemplate.opsForValue().set(key, value, time, TimeUnit.MINUTES);
    }

    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除缓存
     * @param pattern
     */
    public void deleteCache(String pattern){
        Set<String> keys = redisTemplate.keys(pattern);
        if (keys.isEmpty()){
            return;
        }
        redisTemplate.delete(keys);
    }
}
